//
//  AouthViewController.swift
//  Weibo
//
//  Created by 张小东 on 16/1/13.
//  Copyright © 2016年 Mr.Zhang. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    // 设置授权页面为webView
    let webView = UIWebView()
    
    // 关闭授权页面
    @objc private func closeWebView() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    // 实现自动填充账号功能
    @objc private func defaultAddUserInfo() {
        
        let script = "document.getElementById('userId').value = 'kokozzxd@163.com' , document.getElementById('passwd').value = 'che963.'"
        webView.stringByEvaluatingJavaScriptFromString(script)
        
    }
    // 重写loadView 将根视图设置为webView
    override  func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航条
        setNavBar()
        // MARK 加载授权页面
        loadOAuthInfo()
    }
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeWebView")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAddUserInfo")
    }
    // 加载授权页面
    private func  loadOAuthInfo() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=160251041&redirect_uri=http://www.itcast.cn"
        let url = NSURL(string: urlString)!
        let ruquest = NSURLRequest(URL: url)
        webView.loadRequest(ruquest)
    }
    
}

extension OAuthViewController : UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    // webView协议的最重要的方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //        print(request.URL?.absoluteString)
        guard let urlStr = request.URL?.absoluteString else {
            //如果无法获取url字符串  直接返回 不加载界面
            return false
        }
        if urlStr.containsString("code") {
            print("===",urlStr)
            // 将url中的参数获取到
            guard let query = request.URL?.query else {
                return false
            }
            let codeStr = "code="
            // 将query转换成NSString  subString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            print(code,query)
            
            // 调用获取token的方法
            loadAccessToken(code)
            // 不跳转到回调页面
            return false
        }
        
        return true
    }
    
    private func loadAccessToken(code: String) {
        // 请求token和用户信息
        UserAccountModel().loadAccessToken(code) { (isSuccess : Bool) -> () in
            if !isSuccess {
                
                print("用户登录失败")
                SVProgressHUD.showErrorWithStatus("网络正在开小差,请稍后再试...")
                return
            }
        
            // 登陆成功
            SVProgressHUD.showSuccessWithStatus("恭喜您,登陆成功")
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                
                // 发出通知
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVC, object: "还没有登陆,跳转到访客界面")
                })

        }
    }
}
